<?php
declare (strict_types=1);

namespace app\scan_bag\controller;

use aliyun\AliyunOss;
use app\admin\model\base\User;
use app\admin\model\iot\ScanBagDay;
use app\admin\model\iot\ScanBagWay;
use app\admin\service\base\JwtService;
use app\BaseController;
use app\BaseService;
use app\scan_bag\service\ScanBagV2Service;
use redis\RedisTools;
use think\App;
use think\facade\Cache;
use think\response\Json;
use wechat\WsOfficialAccount;

/**
 * 微信V2_Way_4_0扫码取袋
 */
class V2_Way_4_0 extends BaseController
{

    /**
     * 当前扫码路径
     * @var string
     */
    private string $way = 'V2_Way_4_0';

    /**
     * 微信H5用户登录
     * @param ScanBagV2Service $scanBagV2Service
     * @return Json
     */
    public function wechatLogin(ScanBagV2Service $scanBagV2Service): Json
    {
        //接受参数
        $code = $this->request->param('code/s', '');
        //微信解析code
        $bool = $scanBagV2Service->wechatH5Login2($code);
        if ($bool['bool']) {
            //签发token
            $jst_data = JwtService::authorizations('scan_bag', $bool['user_id'], 3600);
            if ($jst_data['bool']) {
                return jsonReturn(1, $bool, '登录成功');
            }
        }
        return jsonReturn(0, [], '签发token失败');
    }

    /**
     * 微信H5用户取袋次数
     * @return Json
     */
    public function userScanNum(): Json
    {
        $user_id = WS_USER_ID;
        $day = ScanBagDay::getUserIdDayNum($user_id);
        return jsonReturn(1, $day);
    }

    /**
     * 微信H5公众号二维码
     * @return Json
     */
    public function wechatQrcode(): Json
    {
        //接受参数
        $user_id = WS_USER_ID;
        $mac_id = $this->request->param('mac_id/s');
        if (!$mac_id) {
            return jsonReturn(0, [], 'MacID参数错误');
        }
        //显示兜底公众号二维码
        $sys_config = config('sys_config.WsOfficialAccount');
        //未关注默认主体公众号二维码
        $name = $sys_config['name'];
        $appid = $sys_config['appid'];
        //获取带参数的二维码url
        $Ws = new WsOfficialAccount();
        $qrcode = $Ws->temporaryQrcode('scan_bag');
        $data = ['name' => $name, 'appid' => $appid, 'qrcode' => $qrcode];
        //标记取袋安全码
        $SafeCode = ScanBagV2Service::getBagOutSafeCode($user_id, $this->way, $mac_id, 1);
        if (!$SafeCode) {
            return jsonReturn(0, [], '请重新扫描屏幕上的二维码');
        }
        return jsonReturn(1, $data);
    }

    /**
     * 微信H5识别二维码
     * @return Json
     */
    public function qrcodeDiscern(): Json
    {
        //接受参数
        $user_id = WS_USER_ID;
        $mac_id = $this->request->param('mac_id/s');
        if (!$mac_id) {
            return jsonReturn(0, [], 'MacID参数错误');
        }
        //标记取袋安全码
        $SafeCode = ScanBagV2Service::getBagOutSafeCode($user_id, $this->way, $mac_id, 2);
        if (!$SafeCode) {
            return jsonReturn(0, [], '请重新扫描屏幕上的二维码');
        }
        return jsonReturn(1, []);
    }

    /**
     * 获取JSAPI配置
     * @return Json
     */
    public function jsApiConfig(): Json
    {
        //接受参数
        $url = $this->request->param('url/s', '');
        $obj = new WsOfficialAccount();
        $data = $obj->getJsApi($url);;
        return jsonReturn(1, $data);
    }

    /**
     * 微信上传经纬度信息
     * @return Json
     */
    public function wechatLatLon(): Json
    {
        //接受参数
        $user_id = WS_USER_ID;
        $mac_id = $this->request->param('mac_id/s');
        $latitude = $this->request->param('latitude/s', '0');
        $longitude = $this->request->param('longitude/s', '0');
        if (!$mac_id) {
            return jsonReturn(0, [], 'MacID参数错误');
        }
        //把地理位置信息保存至用户表
        User::userLocationRedis($user_id, $mac_id, $latitude, $longitude);
        //微信验证上传经纬度信息
        $bool = ScanBagV2Service::verifyLatLon($mac_id, $latitude, $longitude);
        if ($bool) {
            return jsonReturn(1, [], '验证通过');
        }
        return jsonReturn(1, [], '验证通过');
        return jsonReturn(0, [], '您的位置距离设备太远,请移步设备前扫码免费领取。');
    }

    /**
     * 微信取袋码出袋
     * @return Json
     */
    public function postOutBag(): Json
    {
        //接收参数
        $user_id = WS_USER_ID;
        $mac_id = $this->request->param('mac_id/s', '');
        //判断参数
        if (!$user_id or !$mac_id) {
            return jsonReturn(0, [], 'MacID参数错误');
        }
        //获取用户信息
        $User = User::getIdUserInfo($user_id);
        //标记取袋安全码
        $SafeCode = ScanBagV2Service::getBagOutSafeCode($user_id, $this->way, $mac_id, 3, true);
        if (!$SafeCode) {
            return jsonReturn(0, [], '请重新扫描屏幕上的二维码!');
        }
        //验证当前设备取袋路径
        $WayInfo = ScanBagWay::getMacIdWay($mac_id);
        if ($WayInfo['key'] != $this->way) {
            return jsonReturn(0, [], '当前设备路径错误,请联系管理员!');
        }
        //获取缓存当前用户经纬度
//        $LatLon = Cache::get(BaseService::generateLocationKey($user_id));
//        if (!$LatLon or !isset($LatLon['latitude']) or !isset($LatLon['longitude'])) {
//            return jsonReturn(0, [], '您的位置授权失败,请重新扫描屏幕上的二维码!');
//        }
        //验证地理位置
//        $bool = ScanBagV2Service::verifyLatLon($mac_id, $LatLon['latitude'], $LatLon['longitude']);
//        if (!$bool) {
//            return jsonReturn(0, [], '您的位置距离设备太远,请移步设备前扫码免费领取!');
//        }
        //生成取袋码
        $waycode = ScanBagV2Service::generateBagOutWaycode($User, $WayInfo['key'], $mac_id);
        //执行出袋程序
        sleep(7);
        $res = ScanBagV2Service::bagOutProgram($waycode, $this->way, $user_id, $mac_id,7);
        if ($res['bool']) {
            //生成数据缓存，方便用户查询是否出袋成功(缓存50s)
            Cache::set($user_id.'_c','1',50);
            return jsonReturn(1, $res['data'], $res['msg']);
        }
        return jsonReturn(0, [], $res['msg']);
    }

    /**
     * 微信取袋发起支付
     * @return Json
     */
    public function wechatPayOrder(): Json
    {
        $user_id = WS_USER_ID;
        $mac_id = $this->request->param('mac_id', '');
        //判断参数
        if (!$user_id or !$mac_id) {
            return jsonReturn(0, [], '用户信息或设备地址错误!');
        }
        //执行发起预支付
        $res = ScanBagV2Service::wechatPayOrder($user_id, $mac_id);
        if ($res['bool']) {
            return jsonReturn(1, $res['data'], $res['msg']);
        }
        return jsonReturn(0, [], $res['msg']);
    }

    /**
     * 获取出袋成功后跳转
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getRedirectUrl():Json
    {
        $url = ScanBagWay::where('key','=','V2_Way_4_0')->find();
        if(!empty($url->success_redirect_uri)){
            return jsonReturn(1, ['url'=>$url->success_redirect_uri]);
        }
        return jsonReturn(0, [],'暂无url');
    }

    /**
     * 获取配置的视频号链接
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getVideoUrl():Json
    {

        $user_id = WS_USER_ID;
        $mac_id = $this->request->param('mac_id', '');
        if (!$mac_id) {
            return jsonReturn(0, [], '参数错误');
        }
        //标记取袋安全码
        $SafeCode = ScanBagV2Service::getBagOutSafeCode($user_id, $this->way, $mac_id, 1);
        if (!$SafeCode) {
            return jsonReturn(0, [], '请重新扫描屏幕上的二维码');
        }
        $info = ScanBagWay::where('key','=','V2_Way_4_0')->find();
        $data = [];
        if($info->secondary){
            $data = \app\admin\model\advertiser\AdvertiserSecondary::getIdAccount($user_id,$info->secondary,$mac_id);
        }
        //显示兜底的小程序二维码
        if(empty($data) && $info->secondary_url){
            $AliyunOss = new AliyunOss();
            $data = [
                'url'=>$info->secondary_url ? $AliyunOss->getObjectUrl($info->secondary_url) : '',
                'type'=>4,
                'name'=>'兜底',
            ];
        }
        $data['is_one_type'] = 1;
        return jsonReturn(1, $data);

        $user_id = WS_USER_ID;
        $mac_id = $this->request->param('mac_id', '');
        if (!$mac_id) {
            return jsonReturn(0, [], '参数错误');
        }
        $url = ScanBagWay::where('key','=','V2_Way_4_0')->find();

        $AliyunOss = new AliyunOss();
        $img_url = $url->video_url ? $AliyunOss->getObjectUrl($url->video_url) : '';
        //标记取袋安全码
        $SafeCode = ScanBagV2Service::getBagOutSafeCode($user_id, $this->way, $mac_id, 1);
        if (!$SafeCode) {
            return jsonReturn(0, [], '请重新扫描屏幕上的二维码');
        }
        return jsonReturn(1, ['url'=>$img_url,'is_one_type'=>$url->is_one_type]);
    }

    /**
     * 查询用户出袋是否成功
     * @return Json
     */
    public function getBagIs():Json
    {
        $user_id = WS_USER_ID;
        $is = Cache::get($user_id.'_c');
        //取完值删除缓存
        Cache::delete($user_id.'_c');
        if($is && $is == '1'){
            return jsonReturn(1, [],'成功');
        }
        return jsonReturn(0, [],'失败');
    }

    /**
     * 统计二次识别次数
     * @return Json
     */
    public function setStatisticsNum():Json
    {
        $user_id = WS_USER_ID;
        $mac_id = $this->request->param('mac_id/s', '');
        $endTime = mktime(23, 59, 59, intval(date("m")), intval(date("d")), intval(date("Y")));
        $endTime = $endTime - time();
        $redis = RedisTools::getInstance(config('cache.stores.redis'), 0)->getRedis();
        $key = 'V2_Way_4_0_'.date('Y-m-d').'_num';
        //标记取袋安全码
        $SafeCode = ScanBagV2Service::getBagOutSafeCode($user_id, $this->way, $mac_id, 2);
        if (!$SafeCode) {
            return jsonReturn(0, [], '请重新扫描屏幕上的二维码');
        }
        if (!$redis->exists($key)) {
            $redis->setex($key, $endTime,1);
        } else {
            $redis->incr($key);
        }
        return jsonReturn(1, []);
    }


}
